<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grid;
use App\Models\Project;
use App\Models\User;
use App\Models\Villager;
use App\Models\Street;
use App\Models\Village;
use App\Models\GridGroup;
use App\Models\AssessCompany;
use App\Models\MappingCompany;
use App\Models\BuildForm;
use App\Models\ProtocolPlan;
use App\Models\GridArea;
use App\Models\GridPlan;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

// 网格
class GridController extends Controller
{
    // 列表
    public function index(Request $request)
    {
        $keywords = $request->input('keywords', ''); // 查询关键字
        $is_all = $request->input('is_all', 0); //不分页获取全部数据
        $village_id = $request->input('village_id', '');

        if ($is_all) {
            $data = Grid::query()
                ->when($keywords, function ($query) use ($keywords) {
                    $query->where('name', 'like', "%{$keywords}%");
                })
                ->when($village_id, function ($query) use ($village_id) {
                    $query->whereIn('village_id', explode(',', $village_id));
                })
                ->where($this->getAppWhere())
                ->with('street:id,name')
                ->with('village:id,name')
                ->with('grid_group:id,name')
                ->with('segment:id,name')
                ->orderBy('id')
                ->get()
                ->toArray();
        } else {
            $data = Grid::query()
                ->when($keywords, function ($query) use ($keywords) {
                    $query->where('name', 'like', "%{$keywords}%");
                })
                ->when($village_id, function ($query) use ($village_id) {
                    $query->whereIn('village_id', explode(',', $village_id));
                })
                ->where($this->getAppWhere())
                ->with('street:id,name')
                ->with('village:id,name')
                ->with('grid_group:id,name')
                ->with('segment:id,name')
                ->orderByDesc('id')
                ->paginate(env('PAGE_SIZE', 10));
        }
        return showData($data);
    }

    // 新增
    public function store(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'name' => 'required|max:20',
            'street_id' => 'required',
            'village_id' => 'required',
            'project_id' => 'required',
            'segment_id' => 'required',
            'grid_group_id' => 'required',
        ], [
            'name.required' => '请输入名称',
            'street_id.required' => '请输入街道',
            'village_id.required' => '请输入村庄',
            'project_id.required' => '请输入项目',
            'segment_id.required' => '请输入号段',
            'grid_group_id.required' => '请输入网格组',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $data = $validate->getData();

        $Info['name'] = $data['name'];
        $Info['street_id'] = $data['street_id'];
        $Info['village_id'] = $data['village_id'];
        $Info['project_id'] = $data['project_id'];
        $Info['segment_id'] = $data['segment_id'];
        $Info['grid_group_id'] = $data['grid_group_id'];

        try {
            $add = Grid::query()->create($Info);
            return showSuccess('添加成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 编辑
    public function update($Id, Request $request)
    {
        if (empty($Id)) {
            return showError('id不能为空!');
        }
        // 验证
        $validate = Validator::make($request->all(), [
            'name' => 'required|max:20',
            'street_id' => 'required',
            'village_id' => 'required',
            'project_id' => 'required',
            'segment_id' => 'required',
            'grid_group_id' => 'required',
        ], [
            'name.required' => '请输入名称',
            'street_id.required' => '请输入街道',
            'village_id.required' => '请输入村庄',
            'project_id.required' => '请输入项目',
            'segment_id.required' => '请输入号段',
            'grid_group_id.required' => '请输入网格组',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $data = $validate->getData();

        $Info['name'] = $data['name'];
        $Info['street_id'] = $data['street_id'];
        $Info['village_id'] = $data['village_id'];
        $Info['project_id'] = $data['project_id'];
        $Info['segment_id'] = $data['segment_id'];
        $Info['grid_group_id'] = $data['grid_group_id'];
        try {
            $update = Grid::query()->where('id', $Id)->update($Info);
            return showSuccess('编辑成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 删除
    public function destroy($id)
    {
        if (empty($id)) {
            return showError('参数错误！');
        }

        $admin = Grid::query()->where('id', $id)->first();
        if (empty($admin)) {
            return showError('删除项不存在');
        }
        try {
            $delete = Grid::query()->where('id', $id)->delete();
            return showSuccess('删除成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 详情
    public function show($id, Request $request)
    {
        if (empty($id)) {
            return showError('参数错误');
        }

        $type = $request->input('type', ''); 
        if($type==1){
            $set_tally=$this->setTally($id,4);
            if (isset($set_tally['code']) && $set_tally['code'] == 0) {
                return $set_tally;
            }
        }
     
        $data = Grid::query()
            ->with('villager')
            ->with('agent')
            ->with('grid_area_arr')
            ->with(['grid_house' => function ($query) {
                $query->with('house_type:id,name,area');
            }])
            ->with(['grid_house_2' => function ($query) {
                $query->where('type', 1)->with('house_type:id,name,area');
            }])
            ->with('grid_img')
            ->with(['grid_price' => function ($query) {
                $query->where('type', 0);
            }])
            ->where('id', $id)
            ->first()
            ->toArray();

        if ($data) {
            $data['business_imgs'] = $data['business_imgs'] ? $this->getImageUrl($data['business_imgs']) : [];

            foreach ($data['villager'] as &$v1) {
                $v1['id_obverse_img'] = $v1['id_obverse_img'] ? $this->getImageUrl($v1['id_obverse_img']) : [];
                $v1['id_reverse_img'] = $v1['id_reverse_img'] ? $this->getImageUrl($v1['id_reverse_img']) : [];
            }

            if ($data['agent']) {
                $data['agent']['id_obverse_img'] = isset($data['agent']['id_obverse_img']) ? $this->getImageUrl($data['agent']['id_obverse_img']) : [];
                $data['agent']['id_reverse_img'] = isset($data['agent']['id_reverse_img']) ? $this->getImageUrl($data['agent']['id_reverse_img']) : [];
            }

            foreach ($data['grid_area_arr'] as &$v2) {
                $v2['do_user_name'] = User::query()->where('id', $v2['do_user_id'])->value('username');
            }

            foreach ($data['grid_house'] as &$v3) {
                $v3['do_user_name'] = User::query()->where('id', $v3['do_user_id'])->value('username');
                $v3['villager'] = Villager::query()->select('id', 'name')->whereIn('id', explode(',', $v3['villager_ids']))->get()->toArray();
            }

            foreach ($data['grid_house_2'] as &$v33) {
                $v33['do_user_name'] = User::query()->where('id', $v33['do_user_id'])->value('username');
                $v33['villager'] = Villager::query()->select('id', 'name')->whereIn('id', explode(',', $v33['villager_ids']))->get()->toArray();
            }

            foreach ($data['grid_img'] as &$v4) {
                $v4['do_user_name'] = User::query()->where('id', $v4['do_user_id'])->value('username');
                $v4['imgs'] = $v4['imgs'] ? $this->getImageUrl($v4['imgs'], 1) : [];
                $li[$v4['type']][] = $v4;
            }
            $data['grid_img_arr'] = $li ?? [];
            unset($data['grid_img']);

            if ($data['grid_price']) {
                $data['grid_price']['do_user_name'] = User::query()->where('id', $data['grid_price']['do_user_id'])->value('username');
            }

            if($type==1){
                $protocol_plan=ProtocolPlan::query()->where('grid_id', $id)->get()->toArray();
                foreach ($protocol_plan as &$v5) {
                    $v5['villager_ids']=explode(',',$v5['villager_ids']);
                }
                $data['protocol_plan']=$protocol_plan;
            }

            $opinion = ['未开始', '同意', '拒绝'];
            $data['opinion'] = $opinion[$data['opinion']];
            $data['project_id'] = Project::query()->where('id', $data['project_id'])->value('name');
            $data['street_id'] = Street::query()->where('id', $data['street_id'])->value('name');
            $data['village_id'] = Village::query()->where('id', $data['village_id'])->value('name');
            $data['grid_group_id'] = GridGroup::query()->where('id', $data['grid_group_id'])->value('name');
            $data['assess_company_id'] = AssessCompany::query()->where('id', $data['assess_company_id'])->value('name');
            $data['mapping_company_id'] = MappingCompany::query()->where('id', $data['mapping_company_id'])->value('name');
            $data['build_form_str'] = BuildForm::query()->where('id', $data['build_form'])->value('name');
            $data['receive_villager_id'] = Villager::query()->where('id', $data['receive_villager_id'])->value('name');
        } else {
            return showError('获取信息失败');
        }

        return showData($data);
    }

    // 拆分网格
    public function splitGrid(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'grid_data' => 'required',
        ], [
            'grid_id.required' => '请输入原网格id',
            'grid_data.required' => '请输入内容',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        try {
            $grid_data = json_decode($params['grid_data'], true);

            $old_grid = Grid::query()->where('id', $params['grid_id'])->first();

            $delete = GridPlan::query()->where('grid_id', $params['grid_id'])->delete();
            $old_area = GridArea::query()->where('grid_id', $params['grid_id'])->get()->toArray();
            if($old_area){
                foreach ($old_area as $vvv) {
                    unset($vvv['id']);
                    unset($vvv['created_at']);
                    unset($vvv['updated_at']);
                    $old_area = GridPlan::query()->create($vvv);
                    $vvv=[];
                }
            }
            
            foreach ($grid_data as $v) {
                $gridData['pid'] = $params['grid_id'];
                $gridData['name'] = $v['name'];
                $gridData['street_id'] = $old_grid['street_id'];
                $gridData['village_id'] = $old_grid['village_id'];
                $gridData['project_id'] = $old_grid['project_id'];
                $gridData['segment_id'] = $old_grid['segment_id'];
                $gridData['grid_group_id'] = $old_grid['grid_group_id'];
                $add1 = Grid::query()->where('id', $params['grid_id'])->create($gridData);

                $villager = explode(',', $v['villager']);
                foreach ($villager as $vv) {
                    $old_villager = Villager::query()->where('id', $vv)->first();
                    $villagerData['grid_id'] = $add1->id;
                    $villagerData['project_id'] = $old_villager['project_id'];
                    $villagerData['name'] = $old_villager['name'];
                    $villagerData['identity_card'] = $old_villager['identity_card'];
                    $villagerData['id_obverse_img'] = $old_villager['id_obverse_img'];
                    $villagerData['id_reverse_img'] = $old_villager['id_reverse_img'];
                    $villagerData['phone'] = $old_villager['phone'];
                    $villagerData['addr'] = $old_villager['addr'];
                    $villagerData['type'] = $old_villager['type'];
                    $villagerData['is_late'] = $old_villager['is_late'];
                    $add2 = Villager::query()->where('id', $params['grid_id'])->create($villagerData);
                }
            }
            return showSuccess('拆分成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 拆分协议
    public function splitProtocol(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'protocol_data' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'protocol_data.required' => '请输入分配内容',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $request->all();
    
        $delete = ProtocolPlan::query()->where('grid_id', $params['grid_id'])->delete();
        try {
            $protocol_data = json_decode($params['protocol_data'], true);

            foreach($protocol_data as $v){
                $Info['grid_id']=$params['grid_id'];
              
                isset($v['villager_ids'])?$Info['villager_ids']=$v['villager_ids']:'';

                isset($v['subsidy_fee'])&&$v['subsidy_fee']!=0?$Info['subsidy_fee']=$v['subsidy_fee']:'';
                isset($v['transition_fee'])&&$v['transition_fee']!=0?$Info['transition_fee']=$v['transition_fee']:'';
                isset($v['require_sign_fee'])&&$v['require_sign_fee']!=0?$Info['require_sign_fee']=$v['require_sign_fee']:'';
                isset($v['require_clear_fee'])&&$v['require_clear_fee']!=0?$Info['require_clear_fee']=$v['require_clear_fee']:'';
                isset($v['if_decorate_fee'])&&$v['if_decorate_fee']!=0?$Info['if_decorate_fee']=$v['if_decorate_fee']:'';
                isset($v['other_subsidy_fee'])&&$v['other_subsidy_fee']!=0?$Info['other_subsidy_fee']=$v['other_subsidy_fee']:'';
                isset($v['house_difference_fee'])&&$v['house_difference_fee']!=0?$Info['house_difference_fee']=$v['house_difference_fee']:'';
                isset($v['stop_fee'])&&$v['stop_fee']!=0?$Info['stop_fee']=$v['stop_fee']:'';
                isset($v['lack_area_fee'])&&$v['lack_area_fee']!=0?$Info['lack_area_fee']=$v['lack_area_fee']:'';
                isset($v['money_fee'])&&$v['money_fee']!=0?$Info['money_fee']=$v['money_fee']:'';
                isset($v['yard_fee'])&&$v['yard_fee']!=0?$Info['yard_fee']=$v['yard_fee']:'';
                isset($v['othe_build_fee'])&&$v['othe_build_fee']!=0?$Info['othe_build_fee']=$v['othe_build_fee']:'';
                isset($v['assess_fee'])&&$v['assess_fee']!=0?$Info['assess_fee']=$v['assess_fee']:'';
                isset($v['use_fee'])&&$v['use_fee']!=0?$Info['use_fee']=$v['use_fee']:'';
                isset($v['subsidiary_fee'])&&$v['subsidiary_fee']!=0?$Info['subsidiary_fee']=$v['subsidiary_fee']:'';
                isset($v['party_a_fee'])&&$v['party_a_fee']!=0?$Info['party_a_fee']=$v['party_a_fee']:'';
                $add=ProtocolPlan::query()->create($Info);
                $Info=[];
            }
            return showSuccess('添加成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }
}
